'use strict';
const db = uniCloud.database()

exports.main = async (event, context) => {
    const collection = db.collection('todo')

    // 获取今天的开始和结束时间
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)

    try {
        // 获取今日统计
        const todayStats = await collection.where({
            createTime: {
                $gte: today,
                $lt: tomorrow
            }
        }).get()

        // 获取全部统计
        const allStats = await collection.get()

        // 获取重要事项统计
        const importantStats = await collection.where({
            strWarn: '重要'
        }).get()

        // 获取默认分组统计
        const defaultGroupStats = await collection.where({
            group: '默认'
        }).get()

        // 处理统计数据
        const todayData = todayStats.data
        const allData = allStats.data
        const importantData = importantStats.data

        return {
            code: 0,
            today: {
                total: todayData.length,
                unfinished: todayData.filter(item => !item.isOver).length,
                finished: todayData.filter(item => item.isOver).length
            },
            all: {
                total: allData.length,
                unfinished: allData.filter(item => !item.isOver).length,
                finished: allData.filter(item => item.isOver).length
            },
            important: {
                total: importantData.length,
                unfinished: importantData.filter(item => !item.isOver).length,
                finished: importantData.filter(item => item.isOver).length
            },
            defaultGroup: defaultGroupStats.data.length
        }
    } catch (error) {
        return {
            code: -1,
            message: '获取统计数据失败'
        }
    }
}